﻿using AnesSystem.Controls;
using AnesSystem.Models;
using AnesSystem.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AnesSystem.ViewModels
{
    public class PacuProcessViewModel : BaseViewModel<PacuProcessViewModel>
    {
        #region Variables
        private bool isNewAddPage;

        #endregion


        #region Constructor

        #endregion


        #region Properties
        public PatientLinkModel CurPatientLink
        {
            get
            {
                return DataManager.Instance.CurrentPatientLink;
            }
        }

        public int CurTotalPage
        {
            get
            {
                return CurPatientLink.Status.PacuPage;
            }
            set
            {
                CurPatientLink.Status.PacuPage = value;
            }
        }

        public bool IsNewAddPage
        {
            get
            {
                return isNewAddPage;
            }

            set
            {
                isNewAddPage = value;
            }
        }

        #endregion


        #region 依赖属性


        #endregion


        #region Event


        #endregion


        #region PrivateMethods

        private void InitPacuData()
        {
            if (!CurPatientLink.Status.InPacuTime.Equals(new DateTime()))
            {
                FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.打印, FunctionListButton.出复苏室);
                CalTotalPage();
                if (CurPatientLink.VitalSignShow != null)
                {
                    List<ConfigVitalSignsModel> list = CurPatientLink.VitalSignShow.PacuVitalSign;
                    if (list == null || list.Count == 0)
                    {
                        CurPatientLink.VitalSignShow.PacuVitalSign.AddRange(PacuRealTimeSignsConfigCtrlViewModel.Instance.GetAutoShow());
                    }
                }
                else
                {
                    CurPatientLink.VitalSignShow.PacuVitalSign.AddRange(PacuRealTimeSignsConfigCtrlViewModel.Instance.GetAutoShow());
                }
                Common.LogHelper.Info(this.GetType(), "入室自动加载生命体征条数：" + PacuRealTimeSignsConfigCtrlViewModel.Instance.GetAutoShow().Count);
                if (CurPatientLink.Status.OutPacuTime.Equals(new DateTime()))
                {
                    if (CurPatientLink.Schedule.Pbssjh.Equals(DataManager.Instance.CurRoom.Name))
                    {
                        VitalSignCapture.Instance.StartCapture();
                    }
                }
                else
                {
                    FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.打印);
                }
                (DataManager.Instance.PacuRecordCtrl.ViewModel as PacuRecordCtrlViewModel).InitData();
            }
            else
            {
                FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.入复苏室);
            }
        }

        private void CalTotalPage()
        {
            DateTime startTime = DataManager.Instance.CurrentPatientLink.Status.PacuStartTime;
            DateTime endTime = DataManager.Instance.CurrentPatientLink.Status.OutPacuTime;
            if (endTime.Equals(new DateTime()))
            {
                endTime = DateTime.Now;
            }
            TimeSpan span = endTime - startTime;
            int minutes = span.Days * 24 * 60 + span.Hours * 60 + span.Minutes;
            int totalPage = (int)minutes / (4 * 60) + 1;
            DataManager.Instance.CurrentPatientLink.Status.PacuPage = totalPage;
            SaveOper2DB();

        }


        private void SaveOper2DB()
        {
            PatientLinkService.Instance.AddUpdate(CurPatientLink);
        }
        #endregion


        #region Public/ProtectedMethods
        public void InPacuClick()
        {
            if (VerifyOperStatus())
            {
                DateTime date = new DateTime();
                CusDatePickerWin win = new CusDatePickerWin();
                win.SelectedDateTime = DateTime.Now;
                win.ShowDialog();
                if (win.Result)
                {
                    date = win.SelectedDateTime;
                }
                if (!date.Equals(new DateTime()))
                {
                    if (date < CurPatientLink.Status.OutRoomTime)
                    {
                        MessageBoxOK ms = new MessageBoxOK("入复苏室时间应该大于出室时间");
                        ms.ShowDialog();
                        return;
                    }
                    if (CurPatientLink.VitalSignShow != null)
                    {
                        List<ConfigVitalSignsModel> list = CurPatientLink.VitalSignShow.PacuVitalSign;
                        if (list == null || list.Count == 0)
                        {
                            CurPatientLink.VitalSignShow.PacuVitalSign.AddRange(PacuRealTimeSignsConfigCtrlViewModel.Instance.GetAutoShow());
                        }
                    }
                    else
                    {
                        CurPatientLink.VitalSignShow.PacuVitalSign.AddRange(PacuRealTimeSignsConfigCtrlViewModel.Instance.GetAutoShow());
                    }
                    Common.LogHelper.Info(this.GetType(), "入室自动加载生命体征条数：" + PacuRealTimeSignsConfigCtrlViewModel.Instance.GetAutoShow().Count);
                    InPacu(date);
                    DateTime startTime = CurPatientLink.Status.PacuStartTime;
                    DateTime endTime = CurPatientLink.Status.OutPacuTime;
                    if (endTime.Equals(new DateTime()))
                    {
                        endTime = DateTime.Now;
                    }
                    TimeSpan span = endTime - startTime;
                    int minutes = span.Days * 24 * 60 + span.Hours * 60 + span.Minutes;
                    int totalPage = (int)minutes / (4 * 60) + 1;
                    CurTotalPage = totalPage;
                    SaveOper2DB();
                    FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.打印, FunctionListButton.出复苏室);
                    VitalSignCapture.Instance.StartCapture();
                    AddEvent(Constants.EVENT_IN_HUIFUSHI, date, true);
                    Common.LogHelper.Info(this.GetType(), "The patient In_Pacu");
                    (DataManager.Instance.PacuRecordCtrl.ViewModel as PacuRecordCtrlViewModel).InitData();
                }

            }
        }

        private void AddEvent(string code, DateTime date, bool isInPacu)
        {
            List<PatientEventsModel> events = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchEventExeByCode(Constants.EVENT_IN_HUIFUSHI);
            if (events != null && events.Count > 0)
            {
                PatientEventsModel pem = events.First();
                if (isInPacu)
                {
                    pem.BeginTime = date;
                }
                else
                {
                    pem.EndTime = date;
                }

                PatientEventsService.Instance.AddUpdate(pem);
                OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(pem);
            }
            else
            {
                PatientEventsModel pem = new PatientEventsModel();
                pem.Code = Constants.EVENT_IN_HUIFUSHI;
                pem.BeginTime = date;
                pem.PatientID = CurPatientLink.Id.ToString();
                PatientEventsService.Instance.AddUpdate(pem);
                OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(pem);
            }

        }

        private void RefreshEvent()
        {
            for (int i = 1; i <= CurTotalPage; i++)
            {
                (DataManager.Instance.PacuRecordCtrl.ViewModel as PacuRecordCtrlViewModel).PacuRecordCtrlViewModels[i].PacuEventAndMedicineCtrlViewModel.Refresh();
            }
        }

        private void InPacu(DateTime date)
        {
            CurPatientLink.Application.Detailstatus = Constants.OR_STATUS_FLAG_IN_PCU;
            CurPatientLink.Application.Status = Constants.AP_STATUS_MAZUIHOU;
            date = date.AddSeconds(-date.Second).AddMilliseconds(-date.Millisecond);
            CurPatientLink.Status.InPacuTime = date;
            date = date.AddMinutes(-date.Minute % 15);
            CurPatientLink.Status.PacuStartTime = date;
            AnesthesiaRecordModel anes = CurPatientLink.AnesthesiaRecord;
            PacuModel pacu = CurPatientLink.Pacu;
            if (string.IsNullOrEmpty(anes.Tsqk) || anes.Tsqk.Equals("无"))
            {
                pacu.Shuqianwu = true;
            }
            else
            {
                pacu.Shuqianyou = true;
                pacu.Tsqk = anes.Tsqk;
            }
            SaveOper2DB();

        }

        private void OutPacu(DateTime date)
        {
            CurPatientLink.Application.Detailstatus = Constants.OR_STATUS_FLAG_OUT_PCU;
            date = date.AddSeconds(-date.Second).AddMilliseconds(-date.Millisecond);
            CurPatientLink.Status.OutPacuTime = date;
            SaveOper2DB();
        }
        private bool VerifyOperStatus()
        {
            string status = CurPatientLink.Application.Detailstatus;
            if (!Constants.OR_STATUS_FLAG_OUT_ROOM.Equals(status))
            {
                MessageBoxCommon.ShowDialog("该病人尚未出手术室!", 0);
                return false;
            }
            return true;
        }

        public void OutPacuClick()
        {
            DateTime date = new DateTime();
            CusDatePickerWin win = new CusDatePickerWin();
            win.SelectedDateTime = DateTime.Now;
            win.ShowDialog();
            if (win.Result)
            {
                date = win.SelectedDateTime;
            }
            if (!date.Equals(new DateTime()))
            {
                if (date < CurPatientLink.Status.InPacuTime)
                {
                    MessageBoxCommon.ShowDialog("出复苏室时间应大于入复苏室时间!", MessageBoxCommon.OK);
                    return;
                }
                if ((date - DataManager.Instance.CurrentPatientLink.Status.InPacuTime).TotalMinutes > 24 * 60)
                {
                    MessageBoxCommon.ShowDialog("复苏时长应小于24小时!", MessageBoxCommon.OK);
                    return;
                }
                FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.打印);
                VitalSignCapture.Instance.StopCapture();
                OutPacu(date);
                AddEvent(Constants.EVENT_IN_HUIFUSHI, date, false);
                CalTotalPage();
                Refresh();
            }
        }



        public void LoadData()
        {
            InitPacuData();
        }

        public void ChangeTotalPage()
        {

            DataManager.Instance.CurrentPatientLink = PatientLinkService.Instance.GetObjById(CurPatientLink.Id.ToString());
            if (DataManager.Instance.PatientLinkCache.ContainsKey(CurPatientLink.Id))
            {
                BaseTableControl ctrl = DataManager.Instance.PacuRecordCtrl;
                ctrl.IsNewCreate = true;
            }
            InitPacuData();

        }

        public override void Refresh()
        {
            DataManager.Instance.CurrentPatientLink = PatientLinkService.Instance.GetObjById(CurPatientLink.Id.ToString());
            if (DataManager.Instance.PatientLinkCache.ContainsKey(CurPatientLink.Id))
            {
                BaseTableControl ctrl = DataManager.Instance.PacuRecordCtrl;
                ctrl.IsNewCreate = true;
            }
            LoadData();
        }

        public void ChangeEvent(string code, bool isEnd)
        {
            if (code.Equals(Constants.EVENT_IN_HUIFUSHI))
            {
                Refresh();
            }
        }


        #endregion


        #region EventHandlers


        #endregion
    }
}
